﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using Common.Model;
using Common.PddApi;
using Common.Service;
using Common.Util;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pinduoduo.From;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using RestSharp;
using Sunny.UI;
using ThumbnailSharp;
using Tk.Soc.Share.Common.Helpers;
using static pinduoduo.Page.MainPage;
using static Sunny.UI.UIImageListBox;

namespace pinduoduo.Page
{
    public partial class OrderPage : UIPage
    {

        private PddTokenService pddTokenService;
        public OrderPage()
        {
            InitializeComponent();

            InitDataGridView();

            pddTokenService = new PddTokenService();

            //this.beforeDateTimePicker.Value = DateTime.Now.AddDays(-7);

            //this.afterDateTimePicker.Value = DateTime.Now;
            this.uiDatetimePickerBefore.Value = DateTime.Now.AddDays(-7);


            this.uiDatetimePickerAfter.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            this.uiDatetimePickerBefore.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 00, 00);
            this.uiDatetimePickerBefore.Value = this.uiDatetimePickerBefore.Value.AddDays(-7);
            ToolStripMenuItem item = new ToolStripMenuItem("与商家假聊");
            ToolStripMenuItem item1 = new ToolStripMenuItem("复制订单号");
            ToolStripMenuItem item2 = new ToolStripMenuItem("付款");
            ToolStripMenuItem item3 = new ToolStripMenuItem("手动评论");
            ToolStripMenuItem item4 = new ToolStripMenuItem("选中订单导出");
            ToolStripMenuItem item5 = new ToolStripMenuItem("修改收货地址");
            ToolStripMenuItem item6 = new ToolStripMenuItem("取消退款");
            item.Click += Item_Click;
            item1.Click += Item_Click;
            item2.Click += Item_Click;
            item3.Click += Item_Click;
            item4.Click += Item_Click;
            item5.Click += Item_Click;
            item6.Click += Item_Click;
            uiContextMenuStrip1.Items.Add(item1);
            uiContextMenuStrip1.Items.Add(item);
            uiContextMenuStrip1.Items.Add(item2);
            uiContextMenuStrip1.Items.Add(item3);
            uiContextMenuStrip1.Items.Add(item4);
            uiContextMenuStrip1.Items.Add(item5);
            uiContextMenuStrip1.Items.Add(item6);
        }

        private async void Item_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
            if (order == null) { return; }

            if (item.Text == "与商家假聊")
            {
                var tokens = pddTokenService.GetShuaDanToken();

                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    return;
                }
                if (token.status == "过期")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return;
                }
                else
                {
                    token = await pddTokenService.CheckePddTokenStatus(token);

                    if (token.status == "过期" || token.status == "未知")
                    {
                        Msg("获取用户信息异常，小号可能过期了", true);
                        return;
                    }
                }

                var response = await PddApi.GetOrderInfo(order, token);
                if (response.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(response.Content))
                {
                    var jo = JObject.Parse(response.Content);
                    var mallId = jo["mall"]["id"].ToString();
                    var thumb_url = jo["order_goods"].FirstOrDefault()?["thumb_url"].ToString();

                    string url = "http://yangkeduo.com/chat_detail.html?order_sn=" + order.orderSn + "&goods_name=" + HttpUtility.UrlEncode(order.goodsName) + "&mall_id=" + mallId + "&from=order&refer_page_name=order_detail";
                    //url = HttpUtility.UrlEncode(url);
                    BrowserNewFrom browserNewFrom = new BrowserNewFrom(url, token);
                    browserNewFrom.ShowDialog();
                }

            }
            else if (item.Text == "修改收货地址")
            {
                var tokens = pddTokenService.GetShuaDanToken();

                string address = "萧伯山----13000007810----广东省 汕尾市 陆丰市 陆丰市G324陆城华廷";
                UIInputDialog.InputStringDialog(ref address, true, "请输入新地址格式");
                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    return;
                }

                if (token.status == "过期")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return;
                }
                else
                {
                    token = await pddTokenService.CheckePddTokenStatus(token);

                    if (token.status == "过期" || token.status == "未知")
                    {
                        Msg("获取用户信息异常，小号可能过期了", true);
                        return;
                    }
                }


                PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();

                var pddAddress = PddService.GetAddress(address, ref pddAddressDBModel);
                if (pddAddress == null)
                {
                    ShowErrorNotifier("地址格式有误");
                    return;
                }

                string addressId = await AddAddress(pddAddress, token, null);

                var res = await PddApi.UpdateAddress2(token, addressId, order.orderSn, null);
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    order.name = pddAddress.name;
                    order.mobile = pddAddress.mobile;
                    order.orderAddr = pddAddressDBModel.address;
                    await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                    ShowSuccessNotifier("修改成功");
                }
                else
                {
                    ShowSuccessNotifier("地址修改失败，可能已经申请，未同意");
                }
                //http://yangkeduo.com/order.html?order_sn=210801-292206695352202&refer_page_name=my_order&refer_page_id=10032_1627816107901_c97g2g2cps&refer_page_sn=10032
                //   string url = "http://yangkeduo.com/order.html?order_sn="+ HttpUtility.UrlEncode( order.orderSn) + "&refer_page_name=my_order&refer_page_id=10032_1627816107901_c97g2g2cps&refer_page_sn=10032";


            }
            else if (item.Text == "取消退款")
            {
                var tokens = pddTokenService.GetShuaDanToken();

                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    return;
                }

                if (token.status == "过期")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return;
                }
                else
                {
                    token = await pddTokenService.CheckePddTokenStatus(token);

                    if (token.status == "过期" || token.status == "未知")
                    {
                        Msg("获取用户信息异常，小号可能过期了", true);
                        return;
                    }
                }


                string url = "http://yangkeduo.com/orders.html?type=1&comment_tab=1&combine_orders=1&refer_page_name=personal&refer_page_sn=10001";
                BrowserNewFrom browserNewFrom = new BrowserNewFrom(url, token);
                browserNewFrom.ShowDialog();
            }
            else if (item.Text == "手动评论")
            {
                ShowInfoNotifier("功能即将上线");
                //Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
                //if (order == null) { return; }
                //Clipboard.SetDataObject(order.orderSn);
            }
            else if (item.Text == "复制订单号")
            {
                Clipboard.SetDataObject(order.orderSn);
            }
            else if (item.Text == "选中订单导出")
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "订单 (*.csv)|*.csv";
                dialog.DefaultExt = ".csv";
                dialog.Title = "保存订单";

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string filename = dialog.FileName;
                    var orderList = GetSelectRows();
                    foreach (var orderItem in orderList)
                    {
                        try
                        {
                            orderItem.goodsMoney = Math.Round((decimal)(Convert.ToDouble(orderItem.goodsMoney) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        }
                        catch { }
                    }
                    var stringBuilder = CsvFileUtility.SaveDataToCSVFile<Order>(orderList.ToList());
                    File.WriteAllText(filename, stringBuilder.ToString());
                    ShowSuccessNotifier("保存成功");
                }

            }
            else if (item.Text == "付款")
            {
                try
                {
                    await AutoPay(order);
                    Msg("任务完成，请手动同步订单最新状态");
                }
                catch (Exception e2)
                {
                    Msg("任务异常");
                }


            }


        }


        private async Task<string> AddAddress(PddAddress pddAddress, PddToken pddToken, string daili, bool isDelAddress = false)
        {

            if (pddAddress == null)
            {
                return null;
            }

            string address_id = "";
            var res = await PddApi.AddAddress(pddToken, pddAddress, daili);
            Msg("地址设置：" + pddAddress.address);

            PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
            pddAddressDBModel.address = pddAddress.address;
            pddAddressDBModel.mobile = pddAddress.mobile;
            pddAddressDBModel.name = pddAddress.name;

            if (res.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(res.Content))
            {
                dynamic dyn = JsonConvert.DeserializeObject(res.Content);
                address_id = dyn.address_id;

                return address_id;
            }
            else
            {
                LogHelper.Logger.Debug("地址设置异常：" + pddAddressDBModel.address);
                LogHelper.Logger.Debug("地址设置异常：" + res.Content);
            }

            return address_id;
        }

        private void InitDataGridView()
        {
            OrderDataGridView.AddCheckBoxColumn("选择", "IsCheck").SetFixedMode(50);
            OrderDataGridView.AddColumn("序号", "num").SetFixedMode(50);
            OrderDataGridView.AddColumn("小号", "uid").SetFixedMode(150);
            OrderDataGridView.AddColumn("店铺", "mallName").SetFixedMode(200);
            OrderDataGridView.AddColumn("订单编号", "orderSn").SetFixedMode(230);
            OrderDataGridView.AddColumn("商品ID", "goodsId").SetFixedMode(130);
            OrderDataGridView.AddColumn("商品名", "goodsName").SetFixedMode(200);
            OrderDataGridView.AddColumn("SKU", "skuName").SetFixedMode(200);
            OrderDataGridView.AddColumn("订单状态", "orderState").SetFixedMode(100);
            OrderDataGridView.AddColumn("物流状态", "logisticsInfo").SetFixedMode(300);
            OrderDataGridView.AddColumn("物流最后更新时间", "last_update_time_logistics").SetFixedMode(200);

            OrderDataGridView.AddColumn("快递单号", "logisticsOrderNo").SetFixedMode(150);
            OrderDataGridView.AddColumn("快递名称", "logisticsCompany").SetFixedMode(150);
            OrderDataGridView.AddColumn("订单类型", "order_type").SetFixedMode(100);

            OrderDataGridView.AddColumn("收货姓名", "name").SetFixedMode(100);
            OrderDataGridView.AddColumn("收货地址", "address").SetFixedMode(250);
            OrderDataGridView.AddColumn("收货电话", "mobile").SetFixedMode(100);

            OrderDataGridView.ReadOnly = true;
            OrderDataGridView.AutoGenerateColumns = false;

            UpdateData();
        }

        public async void UpdateData()
        {
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //orderList = orderList.Reverse().ToList();
            this.OrderDataGridView.DataSource = await SearchData();
            //DataGridViewPagination.DataSource = orderList;
            //DataGridViewPagination.ActivePage = 1;
        }

        private async void uiButton4_Click(object sender, EventArgs e)
        {

            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //if (!string.IsNullOrWhiteSpace(this.MaillTextBox.Text.Trim()))
            //{
            //    orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.mallName) && x.mallName.Contains(this.MaillTextBox.Text.Trim()));
            //}

            //if (!string.IsNullOrWhiteSpace(this.GoodIdTextBox.Text.Trim()))
            //{
            //    orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.goodsId) && x.goodsId.Contains(this.GoodIdTextBox.Text.Trim()));
            //}

            //if (!string.IsNullOrWhiteSpace(this.OrderStatusComboBox.Text.Trim()))
            //{
            //    orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains(this.OrderStatusComboBox.Text.Trim()));

            //} 

            //if (!string.IsNullOrWhiteSpace(this.logisticsOrderNoTextBox.Text.Trim()))
            //{
            //    orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsOrderNo) && x.logisticsOrderNo==this.logisticsOrderNoTextBox.Text.Trim());

            //}

            //if (OrderTypeComboBox.Text != "全部订单")
            //{
            //    orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.order_type) && x.order_type.Contains(this.OrderTypeComboBox.Text));
            //}

            //try
            //{
            //    orderList = orderList.Where(x => Convert.ToDateTime(x.buyTime) > beforeDateTimePicker.Value && Convert.ToDateTime(x.buyTime) < afterDateTimePicker.Value);
            //}
            //catch (Exception)
            //{
            //}

            //if (this.SelectExpressOrderNumberCheckBox.Checked)
            //{
            //    IEnumerable<Order> orders = new List<Order>() ;
            //    var ordesGroups = orderList.GroupBy(x => x.logisticsOrderNo);
            //    foreach (var item in ordesGroups)
            //    {
            //        if (string.IsNullOrWhiteSpace(item.Key))
            //        {
            //            continue;
            //        }
            //        if (item.Count() > 1) 
            //        {
            //            item.ForEach(x => x.IsCheck = true);
            //            item.FirstOrDefault().IsCheck = false;
            //            orders= orders.Concat(item);
            //        } 
            //    }
            //    orderList = orders;
            //}

            //this.OrderDataGridView.DataSource = null;
            //orderList = orderList.Reverse().ToList();
            ;
            this.OrderDataGridView.DataSource = await SearchData();


        }


        private async Task<IEnumerable<Order>> SearchData()
        {
            //this.afterDateTimePicker.Value = DateTime.Now;


            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            if (!string.IsNullOrWhiteSpace(this.MaillTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.mallName) && x.mallName.Contains(this.MaillTextBox.Text.Trim()));
            }

            if (!string.IsNullOrWhiteSpace(this.GoodIdTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.goodsId) && x.goodsId.Contains(this.GoodIdTextBox.Text.Trim()));
            }

            if (!string.IsNullOrWhiteSpace(this.OrderStatusComboBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains(this.OrderStatusComboBox.Text.Trim()));

            }

            if (!string.IsNullOrWhiteSpace(this.orderSnTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.orderSn) && x.orderSn.Contains(this.orderSnTextBox.Text.Trim()));
            }


            if (!string.IsNullOrWhiteSpace(this.logisticsOrderNoTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsOrderNo) && x.logisticsOrderNo == this.logisticsOrderNoTextBox.Text.Trim());

            }

            if (OrderTypeComboBox.Text != "全部订单")
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.order_type) && x.order_type.Contains(this.OrderTypeComboBox.Text));
            }

            try
            {

                orderList = orderList.Where(x => DateTime.Compare(Convert.ToDateTime(x.buyTime), uiDatetimePickerBefore.Value) > 0 && DateTime.Compare(Convert.ToDateTime(x.buyTime), uiDatetimePickerAfter.Value) <= 0);
            }
            catch (Exception)
            {
            }

            if (this.SelectExpressOrderNumberCheckBox.Checked)
            {
                IEnumerable<Order> orders = new List<Order>();
                var ordesGroups = orderList.GroupBy(x => x.logisticsOrderNo);
                foreach (var item in ordesGroups)
                {
                    if (string.IsNullOrWhiteSpace(item.Key))
                    {
                        continue;
                    }
                    if (item.Count() > 1)
                    {
                        item.ForEach(x => x.IsCheck = true);
                        item.FirstOrDefault().IsCheck = false;
                        orders = orders.Concat(item);
                    }
                }
                orderList = orders;
            }
            this.DataGridViewPagination.DataSource = null;
            this.OrderDataGridView.DataSource = null;

            // orderList.ToList().Sort((x, y) => { return Convert.ToDateTime(x.buyTime) > Convert.ToDateTime(y.buyTime) ? 0 : 1; });
            orderList = orderList.Reverse().ToList();
            return orderList;
        }

        private void DataGridViewPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            OrderDataGridView.DataSource = pagingSource;
        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetAllToken();
            var orderList = GetSelectRows();
            foreach (Order order in orderList)
            {
                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }

                if (token.status == "过期")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    continue;
                }
                else
                {
                    token = await pddTokenService.CheckePddTokenStatus(token);

                    if (token.status == "过期" || token.status == "未知")
                    {
                        Msg("获取用户信息异常，小号可能过期了", true);
                        continue;
                    }
                }

                //if (!string.IsNullOrWhiteSpace(order.orderState))
                //{
                //    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货") || order.orderState.Contains("待分享") || order.orderState.Contains("待评价"))
                //    {

                //    }
                //    else
                //    {
                //        this.message.AppendText("订单不需要同步：" + order.uid + "\r\n");
                //    }
                //}
                try
                {
                    bool status = await PddApi.GetOrderStatus(order, token);
                    if (status)
                    {
                        await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                    }
                    else
                    {
                        this.LogRichTextBox.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                    }
                }
                catch
                {


                }


            }
            this.OrderDataGridView.Refresh();
        }

        private async void SyncAllOrderStatusButton_Click(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var tokens = pddTokenService.GetAllToken();
            foreach (var order in orderList)
            {
                OrderStatus orderStatus = new OrderStatus();
                orderStatus.ts = PddApi.GetPddTime();

                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }
                if (!string.IsNullOrWhiteSpace(order.orderState))
                {
                    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货") || order.orderState.Contains("待分享") || order.orderState.Contains("待评价"))
                    {

                    }
                    else
                    {
                        continue;
                    }
                }

                if (token.status == "过期")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    continue;
                }
                else
                {
                    token = await pddTokenService.CheckePddTokenStatus(token);

                    if (token.status == "过期" || token.status == "未知")
                    {
                        Msg("获取用户信息异常，小号可能过期了", true);
                        continue;
                    }
                }



                bool status = await PddApi.GetOrderStatus(order, token);
                if (status)
                {
                    await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                }
                else
                {
                    this.LogRichTextBox.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                }
            }

            orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //this.OrderDataGridView.Rows.Clear();
            this.OrderDataGridView.DataSource = new BindingList<Order>(orderList.ToList());
        }

        private async void uiButton3_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定收货（自动查找已经签收的订单）？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken();
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            var orderList = GetSelectRows();

            foreach (var order in orderList)
            {
                if (!string.IsNullOrWhiteSpace(order.logisticsInfo) && order.logisticsInfo.Contains("已签收"))
                {
                    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                    if (token == null)
                    {
                        this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                        continue;
                    }
                    await GoodsReceived(order, token);
                }

            }
        }

        private async void uiButton2_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定好评（自动查找待评价的订单）？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken(); //DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains("已签收")).ToList();

            foreach (DataGridViewRow item in this.OrderDataGridView.Rows)
            {
                var order = item.DataBoundItem as Order;
                if (!string.IsNullOrWhiteSpace(order.logisticsInfo) && order.logisticsInfo.Contains("已签收"))
                {
                    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                    if (token == null)
                    {
                        this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                        continue;
                    }

                    if (!order.orderState.Contains("待评价"))
                    {
                        continue;
                    }
                    await GoodsReview(order, token);
                }

            }

        }

        private async void uiButton6_Click(object sender, EventArgs e)
        {

            DialogResult dr = MessageBox.Show("是否确定收货？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
            {
                return;
            }

            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;

            List<string> imagePaths = new List<string>();
            if (this.uiImageListBox1.Items.Count > 0)
            {
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;
                    imagePaths.Add(listViewItem.ImagePath);
                }
            }

            await GoodsReceivedAndGoodsReview(tokens, order, this.comment.Text, imagePaths);

        }
        /// <summary>
        /// 订单收货和好评
        /// </summary>
        /// <param name="tokens"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        private async Task GoodsReceivedAndGoodsReview(IEnumerable<PddToken> tokens, Order order, string comment, List<string> imagePaths)
        {
            if (order == null)
            {
                this.LogRichTextBox.AppendText("请选中一行进行操作\r\n");
                return;
            }

            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }

            if (token.status == "过期")
            {
                Msg("获取用户信息异常，小号可能过期了", true);
                return;
            }
            else
            {
                token = await pddTokenService.CheckePddTokenStatus(token);

                if (token.status == "过期" || token.status == "未知")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return;
                }
            }


            string address = string.Empty;
            string errorMsg = string.Empty;
            address = G_Api.GetProxyIp(token.pdd_user_id, out errorMsg);
            if (string.IsNullOrWhiteSpace(address))
            {
                this.LogRichTextBox.AppendText("获取代理地址失败r\n");
                return;
            }
            this.LogRichTextBox.AppendText("使用代理IP：" + address + "\r\n");

            var result = await GoodsReceived(order, token, address);

            if (!result) { return; }

            Thread.Sleep(1000);


            var imagesUrlList = new List<Images>();


            foreach (var imagePath in imagePaths)
            {
                string base64 = null;

                try
                {
                    var resultBytes = new ThumbnailCreator().CreateThumbnailBytes(
                                            thumbnailSize: 900,
                                            imageStream: new FileStream(imagePath, FileMode.Open, FileAccess.Read),
                                            imageFormat: Format.Jpeg
                                        );
                    base64 = "data:image/jpg;base64," + Convert.ToBase64String(resultBytes);
                }
                catch (Exception)
                {
                    base64 = "data:image/jpg;base64," + ImageUtil.ImgToBase64String(imagePath);
                }
                var sign = await PddApi.Signature(token, null, "review_image");
                //var sign = await PddApi.UploadSignature(token);
                if (string.IsNullOrWhiteSpace(sign))
                {
                    this.LogRichTextBox.AppendText("上传图片获取签名失败请重试" + order.uid + "\r\n");
                    return;
                }
                var imageObj = await PddApi.UploadImage(token, sign, base64, null);
                if (imageObj == null)
                {
                    this.LogRichTextBox.AppendText("上传图片失败请重试" + order.uid + "\r\n");
                    return;
                }
                imagesUrlList.Add(imageObj);
                this.LogRichTextBox.AppendText("上传评论图片成功：" + imagePath + "\r\n");
            }

            await GoodsReview(order, token, comment, imagesUrlList, address);
        }

        private async Task GoodsReview(Order order, PddToken token, string comment = null, List<Images> imageUrlList = null, string daili = null)
        {
            Unrated unrated = new Unrated();
            unrated.goods_id = order.goodsId;
            unrated.order_sn = order.orderSn;
            unrated.anonymous = 0;
            unrated.timeline_sync_type = 1;
            unrated.comprehensive_dsr = 5;
            unrated.anti_content = "";
            if (comment != null)
            {
                unrated.comment = comment;
            }
            if (imageUrlList != null && imageUrlList.Count > 0)
            {
                unrated.pictures = imageUrlList;
            }

            string url = "http://mobile.yangkeduo.com/proxy/api/v2/order/goods/review?pdduid=" + order.uid;

            var restclient = new RestClient(url);

            if (!string.IsNullOrWhiteSpace(daili))
            {
                restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            }

            restclient.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("AccessToken", token.PDDAccessToken);
            request.AddHeader("Host", "mobile.yangkeduo.com");
            request.AddHeader("Origin", "http://mobile.yangkeduo.com");
            request.AddHeader("Referer", url);


            request.AddJsonBody(unrated);

            var response = await restclient.ExecuteAsync(request);
            if (!string.IsNullOrWhiteSpace(response.Content) && response.StatusCode == HttpStatusCode.OK)
            {
                order.orderState = "好评完成";
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(order);
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "五星好评成功 \r\n");
            }
            else
            {
                LogHelper.Logger.Debug("好评失败：" + response.Content);
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "五星好评失败 \r\n");
            }
        }

        /// <summary>
        /// 订单收货
        /// </summary>
        /// <param name="order"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task<bool> GoodsReceived(Order order, PddToken token, string daili = null)
        {
            string url = "http://apiv4.yangkeduo.com/order/" + order.orderSn + "/received?pdduid=" + order.uid;

            var restclient = new RestClient(url);


            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 5.1; OPPO R9tm Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36";

            if (!string.IsNullOrWhiteSpace(daili))
            {
                restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            }

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("AccessToken", token.PDDAccessToken);
            request.AddHeader("Host", "apiv4.yangkeduo.com");
            request.AddHeader("Referer", url);
            var response = await restclient.ExecuteAsync(request);
            if (!string.IsNullOrWhiteSpace(response.Content) && (response.Content.Contains("已确认收货，正在前往评价...") || response.Content.Contains("已确认收货成功，请勿重复点击")))
            {
                order.orderState = "待评价";
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(order);
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "收获成功 \r\n");
                return true;
            }
            else
            {
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "收获失败 \r\n");
                this.LogRichTextBox.AppendText(response.Content + "\r\n");
                return false;
            }
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.jpg)|*.jpg";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //string file = dialog.FileName;
                //FileStream fs = File.Open(file, FileMode.Open);
                //ImageUtil.CutForCustom(fs, "D://test//1.jpg", 900, 1200,70);
                foreach (var item in dialog.FileNames)
                {
                    uiImageListBox1.AddImage(item, dialog.FileName);
                }

                //bindListView(file);
            }

        }

        private void uiButton7_Click(object sender, EventArgs e)
        {

            if (this.uiImageListBox1.Items.Count > 0)
            {
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;

                }
                //uiImageListBox1.SelectedItem.ImagePath
                //uiImageListBox1.Items.
            }

            if (uiImageListBox1.SelectedItem != null)
            {
                int index = 0;
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;

                    if (uiImageListBox1.SelectedItem.ImagePath == listViewItem.ImagePath)
                    {
                        break;
                    }
                    index++;
                }
                this.uiImageListBox1.Items.RemoveAt(index);
                //this.uiImageListBox1.Items.where();
            }
        }

        private void OrderDataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            //e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
            e.Row.Cells[1].Value = string.Format("{0}", (e.Row.Index + 1) + (this.DataGridViewPagination.ActivePage - 1) * DataGridViewPagination.PageSize);
        }

        private async void uiButton8_Click(object sender, EventArgs e)
        {

            if (!ShowAskDialog("是否批量评价？ 温馨提示：请按照指定的格式进行存放评论和图片"))
            {
                return;
            }

            string commentsPath = AppDomain.CurrentDomain.BaseDirectory + "好评.txt";
            if (!File.Exists(commentsPath))
            {

                ShowErrorDialog("请先输入评语");
                return;
            }

            // string [] comments = TxtUtil.ReadAllLinesFormatText(commentsPath);
            string[] comments = File.ReadAllLines(commentsPath);
            var tokens = pddTokenService.GetAllToken();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var selectOrders = GetSelectRows();

            string path = AppDomain.CurrentDomain.BaseDirectory + "订单好评";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var ordesGroups = selectOrders.GroupBy(x => x.goodsId);
            foreach (var item in ordesGroups)
            {
                string goodId = item.Key;
                path = AppDomain.CurrentDomain.BaseDirectory + "订单好评\\" + goodId;
                if (!Directory.Exists(path))
                {
                    this.LogRichTextBox.AppendText("产品ID：" + goodId + " 评论文件夹不存在,自动创建\r\n");
                    Directory.CreateDirectory(path);
                    //  continue;
                }
                int index = 1;
                foreach (var order in item)
                {
                    string orderPath = path + "\\" + index;
                    if (!Directory.Exists(orderPath))
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个评论文件夹不存在,自动创建\r\n");
                        Directory.CreateDirectory(orderPath);
                    }

                    //string contenx = orderPath + "\\评论.txt";
                    //if (!File.Exists(contenx))
                    //{
                    //    this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 评论不存在 ,自动创建\r\n");
                    //    File.WriteAllText(contenx,"");
                    //    break;
                    //}

                    string contenx = "";
                    int orderIndex = selectOrders.ToList().IndexOf(order);
                    if (comments.Length > orderIndex)
                    {
                        contenx = comments[orderIndex];
                    }
                    else
                    {

                        Msg("产品ID：" + goodId + "第" + orderIndex + " 个订单 评论不存在 ,不评价\r\n", true);
                        //break;
                    }
                    DirectoryInfo folder = new DirectoryInfo(orderPath);
                    var images = folder.GetFiles("*.jpg");
                    List<string> imagesPaths = new List<string>();
                    if (images.Length < 1)
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 好评图片不存在\r\n");
                        //  break;
                    }
                    else
                    {
                        images.ForEach(x => { imagesPaths.Add(x.FullName); });
                    }


                    // this.LogRichTextBox.AppendText("开始任务：" + goodId + "好评内容" +TxtUtil.ReadAllFormatText(contenx) +" |||  总共："+ imagesPaths.Count+ " 个 好评图片\r\n");

                    await GoodsReceivedAndGoodsReview(tokens, order, contenx, imagesPaths);
                    index++;
                }

            }

        }

        private void OrderPage_MouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    OrderDataGridView.ClearSelection();//清空选择项
                    OrderDataGridView.Rows[e.RowIndex].Selected = true;//获取被选中行索引
                    OrderDataGridView.CurrentCell = OrderDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    uiContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
                }
            }
        }

        //private void uiContextMenuStrip1_Click(object sender, EventArgs e)
        //{
        //    var contextMenuStrip = sender as Sunny.UI.UIContextMenuStrip;

        //}

        private void OrderDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    OrderDataGridView.ClearSelection();//清空选择项
                    OrderDataGridView.Rows[e.RowIndex].Selected = true;//获取被选中行索引
                    OrderDataGridView.CurrentCell = OrderDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    uiContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
                }
            }
        }

        //private async void toolStripMenuItem1_Click(object sender, EventArgs e)
        //{
        //   var item = sender as ToolStripMenuItem;
        //    Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
        //    if (order == null) { return; }
        //    if (item.Text == "复制订单号")
        //    {

        //        Clipboard.SetDataObject(order.orderSn);
        //    }
        //    else if (item.Text == "付款")
        //    {
        //      await AutoPay(order);
        //    }
        //}

        private async Task<PayResult> AutoPay(Order order)
        {
            //bool status = await PddApi.GetOrderStatus(order, token);
            //if (status)
            //{
            //    await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
            //    this.LogRichTextBox.AppendText("已申请退款，请点击同步数据确认：" + order.uid + "\r\n");
            //}


            var tokens = pddTokenService.GetAllToken();

            var pddToken = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (pddToken == null)
            {
                Msg("小号没找到：" + order.uid + "", true);
                return PayResult.Ignore;
            }

            if (pddToken.status == "过期")
            {
                Msg("获取用户信息异常，小号可能过期了", true);
                return PayResult.Ignore;
            }
            else
            {
                pddToken = await pddTokenService.CheckePddTokenStatus(pddToken);

                if (pddToken.status == "过期" || pddToken.status == "未知")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return PayResult.Ignore;
                }
            }


            bool status = await PddApi.GetOrderStatus(order, pddToken);
            if (status)
            {
                await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
            }

            if (order.orderState != "未支付" && order.orderState != "待支付")
            {
                Msg("订单已经付款", true);
                return PayResult.Ignore;
            }
            string errorMsg = string.Empty;
            //PddService.GetProxyIp(true,errorMsg);
            var tutpl = await PddService.GetProxyIp(pddToken.pdd_user_id, true, errorMsg);

            string daili = tutpl.Item1;
            string msg = tutpl.Item2;

            if (string.IsNullOrEmpty(daili))
            {
                ShowErrorDialog("获取代理地址失败");
                return PayResult.No;
            }
            IRestResponse res;
            string url;
            if (order.order_type == "批发订单")
            {
                res = await PddPiFaApi.PiFPrepay(pddToken, order.parent_order_sn, daili);

                if (res.StatusCode != HttpStatusCode.OK)
                {
                    Msg("批发生成支付链接失败", true);
                    LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                    return PayResult.Ignore;
                }

                Msg("生成支付链接成功");

                var jo = JObject.Parse(res.Content);
                var queryJo = jo["query"];
                var total_fee = jo["query"]["total_fee"].ToString();

                var gateway_url = jo["gateway_url"];

                StringBuilder stringBuilder = new StringBuilder();
                foreach (JToken grandChild in queryJo)
                {
                    var p = grandChild as JProperty;
                    string s = p.Name + ":" + p.Value;
                    stringBuilder.Append(p.Name);
                    stringBuilder.Append("=");
                    stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
                    stringBuilder.Append("&");
                }
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
                url = gateway_url + "?" + stringBuilder.ToString();
                order.pay_url = url;
                order.goodsMoney = double.Parse(total_fee) * 100 + "";
            }
            else
            {
                PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
                pDDOrderPrepay.pay_app_id = 9;
                pDDOrderPrepay.version = 3;
                pDDOrderPrepay.order_sn = order.orderSn;
                pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + order.orderSn + "&prepay_type=";
                pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

                res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

                if (res.StatusCode != HttpStatusCode.OK)
                {
                    Msg("下单失败,订单预付失败", true);
                    return PayResult.Ignore;
                }

                //订单预付
                PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
                try
                {
                    pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

                }
                catch (Exception e1)
                {
                    LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                    Msg("下单失败,订单预付失败", true);
                    return PayResult.Ignore;
                }

                Msg("生成支付链接成功");

                string query = GetUriParam(pDDOrderPrepayResponse.query);
                url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            }

            order.pay_url = url;
            order.orderState = "待支付";
            await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);


            AutoPayFrom browserFrom = new AutoPayFrom(url, Global.Global.PayPassword);

            var res11 = browserFrom.ShowDialog();

            if (!string.IsNullOrWhiteSpace(order.address_id))
            {
                await PddApi.DelAddressById(pddToken, order.address_id, daili);
            }

            if (res11 == DialogResult.OK)
            {
                return PayResult.OK;
            }
            return PayResult.Ignore;
        }


        /// <summary>
        /// Model对象转换为uri网址参数形式
        /// </summary>
        /// <param name="obj">Model对象</param>
        /// <param name="url">前部分网址</param>
        /// <returns></returns>
        public static string GetUriParam(object obj, string url = "")
        {
            PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            StringBuilder sb = new StringBuilder();
            sb.Append(url);
            //sb.Append("?");
            foreach (var p in propertis)
            {
                var v = p.GetValue(obj, null);
                if (v == null) v = "";

                sb.Append(p.Name);
                sb.Append("=");
                sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式，HttpUtility.UrlEncode是小写
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }

        private void Msg(string msg, bool error = false, bool enter = true)
        {
            if (error) this.LogRichTextBox.SelectionColor = Color.Red;

            LogRichTextBox.AppendText(msg);

            if (enter) LogRichTextBox.AppendText("\r\n");

            if (error) this.LogRichTextBox.SelectionColor = Color.Black;
        }
        private void OrderDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)(this.OrderDataGridView.Rows[this.OrderDataGridView.CurrentCell.RowIndex].Cells[0]);
            if (Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue) == false)
            {
                dataGridViewCheckBoxCell.Value = true;
            }
            else
            {
                dataGridViewCheckBoxCell.Value = false;
            }
        }

        private async void uiButton9_Click(object sender, EventArgs e)
        {
            var orderList = GetSelectRows();
            if (orderList.Count() == 0)
            {
                ShowWarningDialog("请先勾选要删除的数据");
                return;
            }
            if (ShowAskDialog("是否删除选中的" + orderList.Count() + "条数据？删除了不可恢复，请慎重使用"))
            {
                foreach (var item in orderList)
                {
                    DataBaseHelper.SqLiteDBCon.Delete(item);
                }
                ShowSuccessNotifier("删除完成");
                orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
                orderList = orderList.Reverse().ToList();
                DataGridViewPagination.DataSource = orderList;
                DataGridViewPagination.ActivePage = 1;
            }
        }

        private void OrderDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        public IEnumerable<Order> GetSelectRows()
        {
            var orderList = new List<Order>();
            foreach (DataGridViewRow dataGridViewRow in this.OrderDataGridView.Rows)
            {
                var order = dataGridViewRow.DataBoundItem as Order;
                if (order.IsCheck)
                {
                    orderList.Add(order);
                }
            }
            return orderList;
        }

        private void OrderDataGridView_SelectIndexChange(object sender, int index)
        {

        }

        private async void uiButton10_Click(object sender, EventArgs e)
        {

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "订单 (*.csv)|*.csv";
            dialog.DefaultExt = ".csv";
            dialog.Title = "保存订单";

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filename = dialog.FileName;
                var orderList = await SearchData();
                foreach (var item in orderList)
                {
                    try
                    {
                        item.goodsMoney = Math.Round((decimal)(Convert.ToDouble(item.goodsMoney) / Convert.ToDouble(100)), 2).ToString() + " 元";
                    }
                    catch { }
                }
                var stringBuilder = CsvFileUtility.SaveDataToCSVFile<Order>(orderList.ToList());
                File.WriteAllText(filename, stringBuilder.ToString());
                ShowSuccessNotifier("保存成功");
            }
        }

        private void uiCheckBox5_ValueChanged(object sender, bool value)
        {
            foreach (DataGridViewRow dataGridViewRow in this.OrderDataGridView.Rows)
            {
                var order = dataGridViewRow.DataBoundItem as Order;
                order.IsCheck = uiCheckBox1.Checked;
            }
            this.OrderDataGridView.Refresh();
        }

        private void uiContextMenuStrip1_Click(object sender, EventArgs e)
        {

        }

        //private async void PayToolStripMenuItem_Click(object sender, EventArgs e)
        //{ 
        //    Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
        //    if (order == null) { return; }
        //    await AutoPay(order);
        //    Msg("任务完成，请手动同步订单最新状态");
        //}

        private void uiButton11_Click(object sender, EventArgs e)
        {
            if (!ShowAskDialog("是否自动创建文件夹？ 温馨提示：此操作会将选中的订单进行自动创建文件夹，不会覆盖数据的"))
            {
                return;
            }

            var selectOrders = GetSelectRows();

            string path = AppDomain.CurrentDomain.BaseDirectory + "订单好评";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var ordesGroups = selectOrders.GroupBy(x => x.goodsId);
            foreach (var item in ordesGroups)
            {
                string goodId = item.Key;
                path = AppDomain.CurrentDomain.BaseDirectory + "订单好评\\" + goodId;
                if (!Directory.Exists(path))
                {
                    this.LogRichTextBox.AppendText("产品ID：" + goodId + " 自动创建文件夹\r\n");
                    Directory.CreateDirectory(path);
                }
                int index = 1;
                foreach (var order in item)
                {
                    string orderPath = path + "\\" + index;
                    if (!Directory.Exists(orderPath))
                    {
                        Directory.CreateDirectory(orderPath);
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个，自动创建文件夹\r\n");
                    }

                    string contenx = orderPath + "\\评论.txt";
                    if (!File.Exists(contenx))
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 评论不存在 ,自动创建\r\n");
                        File.WriteAllText(contenx, "");
                    }

                    index++;
                    //string contenx = orderPath + "\\评论.txt";
                    //if (!File.Exists(contenx))
                    //{
                    //    this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 评论不存在\r\n");
                    //    break;
                    //}
                }
            }

        }

        private async void uiButton12_Click(object sender, EventArgs e)
        {

            if (!ShowAskDialog("是否将选中的订单进行退款？"))
            {
                return;
            }

            var tokens = pddTokenService.GetAllToken();

            var orderList = GetSelectRows();

            foreach (var order in orderList)
            {

                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }


                if (token.status == "过期")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    continue;
                }
                else
                {
                    token = await pddTokenService.CheckePddTokenStatus(token);

                    if (token.status == "过期" || token.status == "未知")
                    {
                        Msg("获取用户信息异常，小号可能过期了", true);
                        continue;
                    }
                }

                PddService.AfterSales(token, order);
                try
                {
                    bool status = await PddApi.GetOrderStatus(order, token);
                    if (status)
                    {
                        await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                        this.LogRichTextBox.AppendText("已申请退款，请点击同步数据确认：" + order.uid + "\r\n");
                    }
                    else
                    {
                        this.LogRichTextBox.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                    }
                }
                catch
                {

                }

            }
            this.OrderDataGridView.Refresh();

        }

        private void uiGroupBox1_Click(object sender, EventArgs e)
        {

        }

        private void uiButton2_Click_1(object sender, EventArgs e)
        {

        }

        private async void uiButton2_Click_2(object sender, EventArgs e)
        {
            string comment = "";
            UIInputDialog.InputStringDialog(ref comment, true, "请输入追评内容");

            if (string.IsNullOrWhiteSpace(comment))
            {
                ShowErrorNotifier("请输入评论再操作");
                return;
            }

            DialogResult dr = MessageBox.Show("是否追加评论？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
            {
                return;
            }



            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }


            if (token.status == "过期")
            {
                Msg("获取用户信息异常，小号可能过期了", true);
                return;
            }
            else
            {
                token = await pddTokenService.CheckePddTokenStatus(token);

                if (token.status == "过期" || token.status == "未知")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return;
                }
            }

            string urlAnti = "http://mobile.yangkeduo.com/proxy/api/order/goods/review/append";
            string ant = FackUtil.GetAnti(null, urlAnti);

            var res = await PddApi.ReviewAppend(token, order.orderSn, comment, ant);
            if (res.StatusCode == HttpStatusCode.OK)
            {
                Msg("追评成功");
            }
            Console.WriteLine(res);
        }

        private async void uiButton3_Click_1(object sender, EventArgs e)
        {

            var bytes = File.ReadAllBytes(@"D:\ceshi\2.mp4");


            DialogResult dr = MessageBox.Show("是否追加评论？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
            {
                return;
            }



            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }
            var upload_sign = await PddApi.Signature(token, "", "review_video");

            if (string.IsNullOrWhiteSpace(upload_sign))
            {
                Msg("视频获取签名异常！", true);
                return;
            }
            //{"url":"https://video2.pddpic.com/review_video/2021-08-07/2f5107a2f9e4ebf755b1add91a90922a","md5":"8ab6e2105c15b5bf96024fab7c5f744b"}
            var res = await PddApi.UploadVideo(bytes, token);
            if (res.StatusCode == HttpStatusCode.OK)
            {
                var jo = JObject.Parse(res.Content);
                var url = jo["url"].ToString();
                var md5 = jo["md5"].ToString();
                Msg("追评成功");
                var imagesUrlList = new List<Images>();
                await GoodsReview(order, token, "", imagesUrlList);
                // var res = await PddApi.ReviewAppend(token, order.orderSn, this.comment.Text, ant);
            }
            Console.WriteLine(res);
        }

        private async void uiButton3_Click_2(object sender, EventArgs e)
        {

        }

        private void OrderDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private async void uiButton3_Click_3(object sender, EventArgs e)
        {
            if (!ShowAskDialog("是否进行模拟评价，此操作验证评论和订单是否匹配，不会提交评价的"))
            {
                return;
            }

            string commentsPath = AppDomain.CurrentDomain.BaseDirectory + "好评.txt";
            if (!File.Exists(commentsPath))
            {

                ShowErrorDialog("请先输入评语");
                return;
            }
            string[] comments = File.ReadAllLines(commentsPath);
            // string[] comments = TxtUtil.ReadAllLinesFormatText(commentsPath);
            var tokens = pddTokenService.GetAllToken();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var selectOrders = GetSelectRows();

            string path = AppDomain.CurrentDomain.BaseDirectory + "订单好评";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var ordesGroups = selectOrders.GroupBy(x => x.goodsId);
            foreach (var item in ordesGroups)
            {
                string goodId = item.Key;
                path = AppDomain.CurrentDomain.BaseDirectory + "订单好评\\" + goodId;
                if (!Directory.Exists(path))
                {
                    this.LogRichTextBox.AppendText("产品ID：" + goodId + " 评论文件夹不存在,自动创建\r\n");
                    Directory.CreateDirectory(path);
                    //  continue;
                }
                int index = 1;
                foreach (var order in item)
                {
                    string orderPath = path + "\\" + index;
                    if (!Directory.Exists(orderPath))
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个评论文件夹不存在,自动创建\r\n");
                        Directory.CreateDirectory(orderPath);
                    }
                    string contenx = "";
                    int orderIndex = selectOrders.ToList().IndexOf(order);
                    if (comments.Length > orderIndex)
                    {
                        contenx = comments[orderIndex];
                    }
                    else {

                        Msg("产品ID：" + goodId + "第" + orderIndex + " 个订单 评论不存在 ,默认 不评价\r\n", true);
                        // break;
                    }

                    //string contenx = orderPath + "\\评论.txt";
                    //if (!File.Exists(contenx))
                    //{
                    //    this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 评论不存在 ,自动创建\r\n");
                    //    File.WriteAllText(contenx, "");
                    //    break;
                    //}
                    DirectoryInfo folder = new DirectoryInfo(orderPath);
                    var images = folder.GetFiles("*.jpg");
                    List<string> imagesPaths = new List<string>();
                    if (images.Length < 1)
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 好评图片不存在\r\n");
                        //  break;
                    }
                    else
                    {
                        images.ForEach(x => { imagesPaths.Add(x.FullName); });
                    }


                    this.LogRichTextBox.AppendText("开始任务：" + goodId + "好评内容" + contenx + " |||  总共：" + imagesPaths.Count + " 个 好评图片\r\n");

                    index++;
                }

            }


        }

        private async void uiButton13_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定收货？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
            {
                return;
            }

            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;

            List<string> imagePaths = new List<string>();
            if (this.uiImageListBox1.Items.Count > 0)
            {
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;
                    imagePaths.Add(listViewItem.ImagePath);
                }
            }

            if (order == null)
            {
                this.LogRichTextBox.AppendText("请选中一行进行操作\r\n");
                return;
            }

            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }

            if (token.status == "过期")
            {
                Msg("获取用户信息异常，小号可能过期了", true);
                return;
            }
            else
            {
                token = await pddTokenService.CheckePddTokenStatus(token);

                if (token.status == "过期" || token.status == "未知")
                {
                    Msg("获取用户信息异常，小号可能过期了", true);
                    return;
                }
            }


            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择MP4文件";
            dialog.Filter = "所有文件(*.mp4)|*.mp4";
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
           

            string videoPath = dialog.FileName;


            //string videoPath = @"D:\ceshi\2.mp4";

            int second = MP4Util.GetMediaTimeLenSecond(videoPath);
            if (second <= 0 || second > 30)
            {
                Msg("视频太短或太长", true);
                return;

            }

            string urlAnti = "https://api.pinduoduo.com/order";
            string ant = FackUtil.GetAnti(null, urlAnti);
            string errorMsg = "";
            var tutpl = await PddService.GetProxyIp(token.pdd_user_id, true, errorMsg);

            string daili = tutpl.Item1;
            string msg = tutpl.Item2;

            if (string.IsNullOrEmpty(daili))
            {
                ShowErrorDialog("获取代理地址失败");
                return;
            }

            var res = await PddApi.VideoReceived(token, order, ant, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {

                Msg("签收失败！", true);
               //return;
            }

            var upload_sign = await PddApi.Signature(token, "", "review_video");

            if (string.IsNullOrWhiteSpace(upload_sign))
            {
                Msg("视频获取签名异常！", true);
                return;
            }

            var bytes = File.ReadAllBytes(videoPath);
 
               res = await PddApi.UploadVideo(bytes, token);
            if (res.StatusCode == HttpStatusCode.OK)
            {
                var jo = JObject.Parse(res.Content);
                var url = jo["url"].ToString();
                var imagesUrlList = new List<Images>();
           
                ant = FackUtil.GetAnti(null, "https://api.pinduoduo.com/order");


                PddOrderVideoReview pddOrderVideoReview = new PddOrderVideoReview();
                pddOrderVideoReview.anonymous = 0;
                pddOrderVideoReview.timeline_sync_type = 1;
                pddOrderVideoReview.review_source = 1;
                pddOrderVideoReview.comment = "非常好用";
                pddOrderVideoReview.order_sn = order.orderSn;
                pddOrderVideoReview.pictures = new List<string>();
                pddOrderVideoReview.goods_id = order.goodsId;
                Video video =   new Video();
                video.music_id = "69196";
                video.height = 1280;
                video.width = 720;
                video.cover_image_height = 1280;
                video.cover_image_width = 720;
                video.size = bytes.Length;
                video.duration = second;
                pddOrderVideoReview.video = video;

                var image =  MP4Util.GetThumbnailByPath(videoPath);
                string base64;
                try
                {
                  
                    var resultBytes = new ThumbnailCreator().CreateThumbnailBytes(
                                            thumbnailSize: 900,
                                            imageBytes: Bitmap2Byte(image),
                                            imageFormat: Format.Jpeg
                                        );
                    base64 = "data:image/jpg;base64," + Convert.ToBase64String(resultBytes);
                }
                catch (Exception)
                {
                    base64 = "data:image/jpg;base64," + Convert.ToBase64String(Bitmap2Byte(image));
                }
                var sign = await PddApi.Signature(token, null, "review_image");
                //var sign = await PddApi.UploadSignature(token);
                if (string.IsNullOrWhiteSpace(sign))
                {
                    this.LogRichTextBox.AppendText("上传图片获取签名失败请重试" + order.uid + "\r\n");
                    return;
                }
                var imageObj = await PddApi.UploadImage(token, sign, base64, null);
                if (imageObj == null)
                {
                    this.LogRichTextBox.AppendText("上传图片失败请重试" + order.uid + "\r\n");
                    return;
                }

                video.cover_image_url = imageObj.url;
                video.url = url;
             
             

                ant = FackUtil.GetAnti(null, "https://api.pinduoduo.com/v2/order/goods/review");
                res = await PddApi.GoodsReviewVideo(token, pddOrderVideoReview, ant, daili);
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    Msg(res.Content);
                }
                else {

                    Msg("评价失败");
                    Msg(res.Content);
                }

                //await GoodsReview(order, token, "", imagesUrlList);
                // var res = await PddApi.ReviewAppend(token, order.orderSn, this.comment.Text, ant);
            }
            Console.WriteLine(res);
            // await GoodsReceivedAndGoodsReview(tokens, order, this.comment.Text, imagePaths);
        }

        public static byte[] Bitmap2Byte(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }
    }
}
